package com.library.service.impl;

import com.library.dao.StaffDao;
import com.library.model.Staff;
import com.library.service.StaffService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class StaffServiceImpl implements StaffService {

    private final StaffDao staffDao;

    public StaffServiceImpl(StaffDao staffDao) {
        this.staffDao = staffDao;
    }

    @Override
    public List<Staff> getAllStaff() {
        return staffDao.findAll();
    }

    @Override
    public List<Staff> getStaffByCriteria(Map<String, Object> criteria) {

        return staffDao.findByCriteria(criteria);
    }

    @Override
    public Staff getStaffById(Long id) {
        if (id == null || id <= 0) {
            return null;
        }
        return staffDao.findById(id);
    }

    @Override
    public Staff getStaffByEmployeeId(String employeeId) {
        if (employeeId == null || employeeId.trim().isEmpty()) {
            return null;
        }
        return staffDao.findByEmployeeId(employeeId);
    }

    @Override
    @Transactional
    public boolean addStaff(Staff staff) {

        if (staff == null) {
            return false;
        }

        if (staff.getName() == null || staff.getName().trim().isEmpty() ||
                staff.getEmployeeId() == null || staff.getEmployeeId().trim().isEmpty()) {
            return false;
        }

        if (staffDao.findByEmployeeId(staff.getEmployeeId()) != null) {
            return false;
        }

        return staffDao.save(staff) > 0;
    }

    @Override
    @Transactional
    public boolean updateStaff(Staff staff) {

        if (staff == null || staff.getId() == null) {
            return false;
        }

        if (staff.getName() == null || staff.getName().trim().isEmpty() ||
                staff.getEmployeeId() == null || staff.getEmployeeId().trim().isEmpty()) {
            return false;
        }

        Staff existingStaff = staffDao.findById(staff.getId());
        if (existingStaff == null) {
            return false;
        }

        if (!existingStaff.getEmployeeId().equals(staff.getEmployeeId()) &&
                staffDao.findByEmployeeId(staff.getEmployeeId()) != null) {
            return false;
        }

        return staffDao.update(staff) > 0;
    }

    @Override
    @Transactional
    public boolean deleteStaff(Long id) {

        if (id == null || id <= 0) {
            return false;
        }

        if (staffDao.findById(id) == null) {
            return false;
        }

        return staffDao.delete(id) > 0;
    }
}
